import 'dart:async';

import 'package:rxdart/rxdart.dart';

import '../../common/test_page.dart';

class DeferTestPage extends TestPage {
  DeferTestPage(super.title) {
    test('Rx.defer', () async {
      const value = 1;

      final stream = _getDeferStream();

      stream.listen(((actual) {
        expect('$actual, $value');
      }));
    });

    test('Rx.defer.multiple.listeners', () async {
      const value = 1;

      final stream = _getBroadcastDeferStream();

      stream.listen(((actual) {
        expect('$actual, $value');
      }));

      stream.listen(((actual) {
        expect('$actual, $value');
      }));
    });

    test('Rx.defer.streamFactory.called', () async {
      var count = 0;

      Stream<int> streamFactory() {
        ++count;
        return Stream.value(1);
      }

      var deferStream = DeferStream(
        streamFactory,
        reusable: false,
      );

      expect(count);

      deferStream.listen(
        ((_) {
          expect(count);
        }),
      );
    });

    test('Rx.defer.reusable', () async {
      const value = 1;

      final stream = Rx.defer(
            () => Stream.fromFuture(
          Future.delayed(
            Duration(seconds: 1),
                () => value,
          ),
        ),
        reusable: true,
      );

      stream.listen((
              (actual) => expect('$actual, $value')
        ),
      );
      stream.listen((
              (actual) => expect('$actual, $value')
        ),
      );
    });

    test('Rx.defer.single.subscription', () async {
      final stream = _getDeferStream();

      try {
        stream.listen(null);
        stream.listen(null);
        expect('true, false');
      } catch (e) {
        expect(e);
      }
    });

    test('Rx.defer.error.shouldThrow.A', () async {
      final streamWithError = Rx.defer(() => _getErroneousStream());

      streamWithError.listen(null,
          onError: (Object e) {
            expect(e);
          });
    });

    test('Rx.defer.error.shouldThrow.B', () {
      final deferStream1 = Rx.defer<int>(() => throw Exception());
      expect(
        deferStream1
      );

      final deferStream2 = Rx.defer<int>(() => throw Exception(), reusable: true);
      expect(
        deferStream2
      );
    });
  }

  Stream<int> _getDeferStream() => Rx.defer(() => Stream.value(1));

  Stream<int> _getBroadcastDeferStream() =>
      Rx.defer(() => Stream.value(1)).asBroadcastStream();

  Stream<int> _getErroneousStream() {
    final controller = StreamController<int>();

    controller.addError(Exception());
    controller.close();

    return controller.stream;
  }


}